package com.happy.shiro.controller;

import com.alibaba.fastjson.JSON;
import com.happy.shiro.dto.LoginRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("auth")
public class AuthController {
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @RequestMapping(value = "login")
    public String login(LoginRequest request) {
        logger.info("name:" + request.getName() + ", password=" + request.getPassword());
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername(request.getName());
        token.setPassword(request.getPassword().toCharArray());
        try {
            subject.login(token);
            logger.info("sessionId:" + subject.getSession().getId());
            Session session = subject.getSession();
            logger.info("session:" + JSON.toJSONString(session));
            for (Object o : session.getAttributeKeys()) {
                logger.info(JSON.toJSONString(o) + ":" + JSON.toJSONString(session.getAttribute(o)));
            }
            logger.info("hasRole:normal " + subject.hasRole("normal"));
            logger.info("hasRole:admin " + subject.hasRole("admin"));
        } catch (AuthenticationException e) {
            logger.error("登录失败", e);
            return "redirect:../login.html";
        }
        return "redirect:../index.html";
    }
}
